from rest_framework import serializers

from snippets.models import Snippet

from django.contrib.auth.models import User


# 如果继承自`serializers.ModelSerializer`那么就不用写下面那一大段代码了，
# 下面的代码会自动创建, create,update 也是自动创建, 更复杂的代码要自己创建
# modify at 2021.05.07
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')

    class Meta:
        model = Snippet
        fields = ['url', 'id', 'highlight', 'owner',
                  'title', 'code', 'linenos', 'language', 'style']
        # read_only_fields = ['owner']


# modify at 2021.05.07
class UserSerializer(serializers.HyperlinkedModelSerializer):
    # snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)

    class Meta:
        model = User
        fields = ['url', 'id', 'username', 'snippets']
